<template>
	<view class="container">
		<view class="layout">
			<view class="block-item" style="overflow: visible">
				<view class="label">新的手机串码</view>
				<view class="input-warp">
					<input class="input" v-model="state.text" type="text" maxlength="12" placeholder="输入手机12位串码" />
					<image class="saoma" @click="saoma" src="@/static/images/saoma.png"></image>
				</view>
				<view class="label">手机故障原因</view>
				<view class="input-warp">
					<uni-data-select class="input" v-model="state.value" :localdata="state.range" placeholder="选择原因"></uni-data-select>
				</view>
				<view class="btn-group">
					<view class="btn-submit" @click="submit">处理完成</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { reactive } from 'vue';
import { get, post } from '@/request/index.js';
import { onLoad } from '@dcloudio/uni-app';

const state = reactive({
	id: '',
	text: '',
	value: '',
	range: []
});

onLoad((option) => {
	state.id = option.order_id;
	getListData();
});

// 获取手机故障原因
const getListData = async () => {
	const res = await get('agent/order/fault_reason');
	const { code, data } = res;
	if (code == 200) {
		state.range = data;
	}
};

//调起相机扫码
const saoma = () => {
	//扫码前先申请调起相机权限
	uni.authorize({
		scope: 'scope.camera',
		success: (res) => {
			// 调起相机进行扫码
			uni.scanCode({
				success: (res2) => {
					// 扫码成功时的回调函数
					console.log('扫码成功：', res2.result);
					state.text = res2.result;
					// 你可以在这里处理扫码得到的结果，例如显示在页面上或发送到服务器
				},
				fail: (err2) => {
					// 扫码失败时的回调函数
					uni.showToast({
						title: err2.errMsg,
						icon: 'none'
					});
					console.error('扫码失败：', err2.errMsg);
					// 你可以在这里处理扫码失败的情况，例如显示错误消息
				}
			});
		},
		fail: (err) => {
			// 拒绝调起相机权限
			uni.showToast({
				title: '您拒绝小程序使用相机权限，无法使用扫码功能',
				icon: 'none'
			});
		}
	});
};

// 提交
const submit = async () => {
	const { text, value, range, id } = state;
	if (!text.length || text.length < 12) {
		return uni.showToast({
			title: '请输入12位串码',
			icon: 'error'
		});
	}
	if (!value.length) {
		return uni.showToast({
			title: '请选择故障原因',
			icon: 'error'
		});
	}
	// const reason = range.find((k) => k.value == value).text;
	const params = {
		order_id: id,
		imei: text,
		reason: value
	};
	const res = await post('agent/order/change_tel', params);
	const { code, message } = res;
	if (code == 200) {
		uni.showToast({
			title: message
		});
		setTimeout(() => {
			uni.navigateBack({
				delta: 1
			});
		}, 2000);
	}
};
</script>
